﻿@using Seal.Model;
@{
    ReportTask task = Model;

    task.TemplateDescription = "Execute the children tasks in parallel (using multiple threads).";

    //Parameters for this task

    task.Script = @"@using System.IO
@using System.Threading
@{
    ReportTask task = Model;
    Report report = task.Report;
    var helper = new TaskHelper(task);
    
    var tasks = new List<Task>();
    int i=1;
    foreach (var child in task.Tasks.Where(i=> i.Enabled).OrderBy(i => i.SortOrder)) {
        var id = $""[{i:00}]"";
        tasks.Add(Task.Run(() => AsyncExec(id, child)));
        Thread.Sleep(10);
        i++;
    }
    
    while (!report.Cancel) {
        Thread.Sleep(100);
        if (!tasks.Exists(i => !i.IsCompleted)) {
            break;
        }    
    }    
}


@functions {
    async Task AsyncExec(string id, ReportTask child) {
    	ReportTask task = Model;
        try {
            task.LogMessage($""Starting Thread: {id} for task {task.Name}"");
            Thread.Sleep(10); 
            child.Execute();
        }
        catch (Exception ex) {
            task.HandleException(ex);
        }
        finally {
            task.LogMessage($""Ending Thread: {id}"");
        }
    }
}
";

    task.BodyScript = ReportTask.NoChildrenBodyScriptTemplate;
}
